#### LOAD IN PACKAGES ####
library(dplyr)
library(haven)
library(tidyverse)
library(car)
library(survey)
library(marginaleffects)
library(ggpubr)
library(kableExtra)
library(knitr)
library(RVAideMemoire)
library(tidyr)
library(xtable)
library(MASS)
library(expss)

sink("../output/inconsistents_main_analysis.log")

####  Load in data  ####
dat22 <- read.csv("../input/CCES22_Common_OUTPUT_vv_topost.csv")
dat20 <- read.csv("../input/CCES20_Common_OUTPUT_vv.csv")
dat21 <- read_sav("../input/CCES21_Common_OUTPUT_timing.sav")
source <- read.csv("../input/CCES22_OUTPUT_sourcevar.csv")

#### merge 2022 data with source ####

dat22 <- merge(dat22, source, all.x=T, by="caseid")

#### DATAPREP for analysis: CREATE INCONSISTENT TAG ####

# Inconsistent tag for police items
dat22$inconsistent <- 0
dat22$inconsistent[dat22$CC22_334c==1 & dat22$CC22_334d==1] <- 1

dat20$inconsistent <- 0
dat20$inconsistent[dat20$CC20_334c==1 & dat20$CC20_334d==1] <- 1

dat21$inconsistent <- 0
dat21$inconsistent[dat21$CC21_321c==1 & dat21$CC21_321d==1] <- 1

# For abortion items
dat22$inconsistenta <- 0
dat22$inconsistenta[dat22$CC22_332a==1 & dat22$CC22_332f==1] <- 1

dat20$inconsistenta <- 0
dat20$inconsistenta[dat20$CC20_332a==1 & dat20$CC20_332f==1] <- 1

dat21$inconsistenta <- 0
dat21$inconsistenta[dat21$CC21_323a==1 & dat21$CC21_323e==1] <- 1

# Create a type variable that combines both inconsistents
dat22$type <- "1 contradiction"
dat22$type[dat22$inconsistent==0 & dat22$inconsistenta==0] <- "No contradictions"
dat22$type[dat22$inconsistent==1 & dat22$inconsistenta==1] <- "2 contradictions"

dat20$type <- "1 contradiction"
dat20$type[dat20$inconsistent==0 & dat20$inconsistenta==0] <- "No contradictions"
dat20$type[dat20$inconsistent==1 & dat20$inconsistenta==1] <- "2 contradictions"


#### Straightliner indicator ####

dat20$abortstraight <- 0
dat20$abortstraight[dat20$CC20_332a==1 & dat20$CC20_332b==1 & dat20$CC20_332c==1 & dat20$CC20_332d==1 & dat20$CC20_332e==1 & dat20$CC20_332f==1] <- 1
dat20$abortstraight[dat20$CC20_332a==2 & dat20$CC20_332b==2 & dat20$CC20_332c==2 & dat20$CC20_332d==2 & dat20$CC20_332e==2 & dat20$CC20_332f==2] <- 1

dat22$abortstraight <- 0
dat22$abortstraight[dat22$CC22_332a==1 & dat22$CC22_332b==1 & dat22$CC22_332c==1 & dat22$CC22_332d==1 & dat22$CC22_332e==1 & dat22$CC22_332f==1] <- 1
dat22$abortstraight[dat22$CC22_332a==2 & dat22$CC22_332b==2 & dat22$CC22_332c==2 & dat22$CC22_332d==2 & dat22$CC22_332e==2 & dat22$CC22_332f==2] <- 1

dat20$crimestraight <- 0
dat20$crimestraight[dat20$CC20_334a==1 & dat20$CC20_334b==1 & dat20$CC20_334c==1 & dat20$CC20_334d==1 & dat20$CC20_334e==1 & dat20$CC20_334f==1 & dat20$CC20_334g==1 & dat20$CC20_334h==1] <- 1
dat20$crimestraight[dat20$CC20_334a==2 & dat20$CC20_334b==2 & dat20$CC20_334c==2 & dat20$CC20_334d==2 & dat20$CC20_334e==2 & dat20$CC20_334f==2 & dat20$CC20_334g==2 & dat20$CC20_334h==2] <- 1

dat22$crimestraight <- 0
dat22$crimestraight[dat22$CC22_334a==1 & dat22$CC22_334b==1 & dat22$CC22_334c==1 & dat22$CC22_334d==1 & dat22$CC22_334e==1 & dat22$CC22_334f==1 & dat22$CC22_334g==1 & dat22$CC22_334h==1] <- 1
dat22$crimestraight[dat22$CC22_334a==2 & dat22$CC22_334b==2 & dat22$CC22_334c==2 & dat22$CC22_334d==2 & dat22$CC22_334e==2 & dat22$CC22_334f==2 & dat22$CC22_334g==2 & dat22$CC22_334h==2] <- 1

dat22$climstraight <- 0
dat22$climstraight[dat22$CC22_333a==1 & dat22$CC22_333b==1 & dat22$CC22_333c==1 & dat22$CC22_333d==1 & dat22$CC22_333e==1] <- 1
dat22$climstraight[dat22$CC22_333a==2 & dat22$CC22_333b==2 & dat22$CC22_333c==2 & dat22$CC22_333d==2 & dat22$CC22_333e==2] <- 1

dat20$climstraight <- 0
dat20$climstraight[dat20$CC20_333a==1 & dat20$CC20_333b==1 & dat20$CC20_333c==1 & dat20$CC20_333d==1] <- 1
dat20$climstraight[dat20$CC20_333a==2 & dat20$CC20_333b==2 & dat20$CC20_333c==2 & dat20$CC20_333d==2] <- 1


dat22$rcstraight <- 0
dat22$rcstraight[dat22$CC22_350a==1 & dat22$CC22_350b==1 & dat22$CC22_350c==1 & dat22$CC22_350d==1 & dat22$CC22_350e==1 & dat22$CC22_350f==1 & dat22$CC22_350g==1 & dat22$CC22_350h==1] <- 1
dat22$rcstraight[dat22$CC22_350a==2 & dat22$CC22_350b==2 & dat22$CC22_350c==2 & dat22$CC22_350d==2 & dat22$CC22_350e==2 & dat22$CC22_350f==2 & dat22$CC22_350g==2 & dat22$CC22_350h==2] <- 1

dat20$rcstraight <- 0
dat20$rcstraight[dat20$CC20_350a==1 & dat20$CC20_350b==1 & dat20$CC20_350c==1 & dat20$CC20_350d==1 & dat20$CC20_350e==1 & dat20$CC20_350f==1 & dat20$CC20_350g==1] <- 1
dat20$rcstraight[dat20$CC20_350a==2 & dat20$CC20_350b==2 & dat20$CC20_350c==2 & dat20$CC20_350d==2 & dat20$CC20_350e==2 & dat20$CC20_350f==2 & dat20$CC20_350g==2] <- 1


#### Figure 1 ####

# Response distribution - policing items ####

police22 <- dat22 %>% group_by(CC22_334c, CC22_334d) %>%   
  summarise(n = n()) %>% na.omit() %>% ungroup() %>%
  mutate(freq = (n / sum(n))*100) %>%
  ggplot(aes(x=as.factor(CC22_334c), y=as.factor(CC22_334d))) +
  geom_tile(aes(fill = freq), colour = "white") +
  geom_text(aes(label = round(freq,0)), size = 10 / .pt, colour="white") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +
  scale_x_discrete(labels=c("Support", "Oppose")) +
  scale_y_discrete(labels=c("Support", "Oppose")) +
  labs(x = "Increase police by 10%", 
       y = "Decrease police by 10%") + theme_minimal() +
  theme(legend.position="none") + ggtitle("2022 - Police Items") 


police20 <- dat20 %>% group_by(CC20_334c, CC20_334d) %>%   
  summarise(n = n()) %>% na.omit() %>% ungroup() %>%
  mutate(freq = (n / sum(n))*100) %>%
  ggplot(aes(x=as.factor(CC20_334c), y=as.factor(CC20_334d))) +
  geom_tile(aes(fill = freq), colour = "white") +
  geom_text(aes(label = round(freq,0)), size = 10 / .pt, colour="white") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +
  scale_x_discrete(labels=c("Support", "Oppose")) +
  scale_y_discrete(labels=c("Support", "Oppose")) +
  labs(x = "Increase police by 10%", 
       y = "Decrease police by 10%") + theme_minimal() +
  theme(legend.position="none") + ggtitle("2020 - Police Items") 


# Response distribution - abortion items ####

abort22 <- dat22 %>% group_by(CC22_332a, CC22_332f) %>%   
  summarise(n = n()) %>% na.omit() %>% ungroup() %>%
  mutate(freq = (n / sum(n))*100) %>%
  ggplot(aes(x=as.factor(CC22_332a), y=as.factor(CC22_332f))) +
  geom_tile(aes(fill = freq), colour = "white") +
  geom_text(aes(label = round(freq,0)), size = 10 / .pt, colour="white") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +
  scale_x_discrete(labels=c("Support", "Oppose")) +
  scale_y_discrete(labels=c("Support", "Oppose")) +
  labs(x = "Always allow abortion", 
       y = "Ban all abortions") + theme_minimal() +
  theme(legend.position="none") + ggtitle("2022 - Abortion Items") 


abort20 <- dat20 %>% group_by(CC20_332a, CC20_332f) %>%   
  summarise(n = n()) %>% na.omit() %>% ungroup() %>%
  mutate(freq = (n / sum(n))*100) %>%
  ggplot(aes(x=as.factor(CC20_332a), y=as.factor(CC20_332f))) +
  geom_tile(aes(fill = freq), colour = "white") +
  geom_text(aes(label = round(freq,0)), size = 10 / .pt, colour="white") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +
  scale_x_discrete(labels=c("Support", "Oppose")) +
  scale_y_discrete(labels=c("Support", "Oppose")) +
  labs(x = "Always allow abortion", 
       y = "Ban all abortions") + theme_minimal() +
  theme(legend.position="none") + ggtitle("2020 - Abortion Items") 

pdf("../output/crosstabs.pdf", width=7, height=6)
ggarrange(police20, police22, abort20, abort22)
dev.off()
print("Figure 1 Done")
#### TABLE 2 INFORMATION ####
print("Contradiction rate, 2020")
prop.table(table(dat20$type))
print("Contradiction rate, 2022")
prop.table(table(dat22$type))
print("Table 2 Printed")



#### TABLE 3 INFORMATION #### 
print("Printing Table 3:")
# row 1: median survey time

# Median total survey time ####
dat22$surveytime <- as.POSIXct(dat22$endtime) - as.POSIXct(dat22$starttime)
dat22$surveytime_min <- as.numeric(dat22$surveytime)
dat20$surveytime <- as.POSIXct(dat20$endtime) - as.POSIXct(dat20$starttime)
dat20$surveytime_min <- as.numeric(dat20$surveytime)
print("Row 1: 2020")
dat20 %>% group_by(type) %>% summarise(median(surveytime_min, na.rm=T))
print("Row 2: 2022")
dat22 %>% group_by(type) %>% summarise(median(surveytime_min, na.rm=T))

# moods median test for the Appendix #
print("Mood's median test used in the Appendix:")
mood.medtest(surveytime_min ~ type, data=subset(dat20, type!="2 contradictions"), exact=FALSE, na.rm=T)
mood.medtest(surveytime_min ~ type, data=subset(dat20, type!="No contradictions"), exact=FALSE, na.rm=T)

mood.medtest(surveytime_min ~ type, data=subset(dat22, type!="2 contradictions"), exact=FALSE, na.rm=T)
mood.medtest(surveytime_min ~ type, data=subset(dat22, type!="No contradictions"), exact=FALSE, na.rm=T)



#### Row 2: proportions test for rc straightlining ####

## 2020 ##
print("Row 2:")
print("Straightlining by contradiction: 2020")
table(dat20$type)
table(dat20$rcstraight, dat20$type)
# 1 contradiction vs. 0
prop.test(x=c(581,3419), n=c(4057,55924))
# 1 contradiction vs. 2
prop.test(x=c(581,435), n=c(4057,1019))
# 2 contradiction vs. 0
prop.test(x=c(435,3419), n=c(1019,55924))
print("Straightlining by contradiction: 2022")
## 2022 ###
table(dat22$type)
table(dat22$rcstraight, dat22$type)
# 1 contradiction vs. 0
prop.test(x=c(1129,13920), n=c(4664,54153))
# 1 contradiction vs. 2
prop.test(x=c(1129,571), n=c(4664,1183))
# 2 contradiction vs. 0
prop.test(x=c(13920,571), n=c(54153,1183))

#### Row 3: Retention #### 
print("Row 3: Retention")
print("2020")
prop.table(table(dat20$tookpost, dat20$type),2)
print("2022")
prop.table(table(dat22$tookpost, dat22$type),2)

## proportions test  ####
print("Row 3 t-test")
### 2020 ####
table(dat20$type)
table(dat20$tookpost, dat20$type)
# 1 contradiction vs. 0
prop.test(x=c(2938,48020), n=c(4057,55924))
# 1 contradiction vs. 2
prop.test(x=c(2938,593), n=c(4057,1019))
# 2 contradiction vs. 0
prop.test(x=c(593,48020), n=c(1019,55924))

### 2022 ####
table(dat20$type)
table(dat22$tookpost, dat22$type)
# 1 contradiction vs. 0
prop.test(x=c(3365,46895), n=c(4664,54153))
# 1 contradiction vs. 2
prop.test(x=c(3365,721), n=c(4664,1183))
# 2 contradiction vs. 0
prop.test(x=c(46895,721), n=c(54153,1183))

#### Row 4: Smart phone indicator ####
dat22$smartphone <- car::recode(dat22$comptype, "1=1; 2:9=0")
dat20$smartphone <- car::recode(dat20$comptype, "1=1; 2:9=0")

print("Row 4: Smartphone Indicator")
### 2020 ####
table(dat20$type)
print("2020")
table(dat20$smartphone, dat20$type)
# 1 contradiction vs. 0
prop.test(x=c(2113,25096), n=c(4057,55924))
# 1 contradiction vs. 2
prop.test(x=c(2113,563), n=c(4057,1019))
# 2 contradiction vs. 0
prop.test(x=c(563,25096), n=c(1019,55924))

### 2022 ####
table(dat22$type)
print("2022")
table(dat22$smartphone, dat22$type)
# 1 contradiction vs. 0
prop.test(x=c(2971,27934), n=c(4664,54153))
# 1 contradiction vs. 2
prop.test(x=c(2971,796), n=c(4664,1183))
# 2 contradiction vs. 0
prop.test(x=c(27934,796), n=c(54153,1183))

#### Row 5: Validated Voter ####
print("Row 5: Validated Voter")
dat20$voter <- 0
dat20$voter[dat20$CL_2020gvm>0] <- 1
print("2020")
prop.table(table(dat20$voter, dat20$inconsistent),2)
prop.table(table(dat20$voter, dat20$type),2)

dat22$voter <- 0
dat22$voter[dat22$TS_g2022<7] <- 1
print("2022")
prop.table(table(dat22$voter, dat22$type),2)

## proportions test  ####
print("Proportions test for row 5")
### 2020 ####
table(dat20$type)
table(dat20$voter, dat20$type)
# 1 contradiction vs. 0
prop.test(x=c(1903,37004), n=c(4057,55924))
# 1 contradiction vs. 2
prop.test(x=c(1903,291), n=c(4057,1019))
# 2 contradiction vs. 0
prop.test(x=c(291,37004), n=c(1019,55924))

### 2022 ####
table(dat22$type)
table(dat22$voter, dat22$type)
# 1 contradiction vs. 0
prop.test(x=c(1631,31766), n=c(4664,54153))
# 1 contradiction vs. 2
prop.test(x=c(1631,176), n=c(4664,1183))
# 2 contradiction vs. 0
prop.test(x=c(31766,176), n=c(54153,1183))

#### Row 6: weight ####
print("Row 6: Average weight")
dat22 %>% group_by(type) %>% summarise(mean(commonweight, na.rm=T))
dat20 %>% group_by(type) %>% summarise(mean(commonweight, na.rm=T))

## Difference of means tests ####
t.test(commonweight ~ type, data=subset(dat22, type!="2 contradictions"))
t.test(commonweight ~ type, data=subset(dat22, type!="No contradictions"))
t.test(commonweight ~ type, data=subset(dat22, type!="1 contradiction"))

t.test(commonweight ~ type, data=subset(dat20, type!="2 contradictions"))
t.test(commonweight ~ type, data=subset(dat20, type!="No contradictions"))
t.test(commonweight ~ type, data=subset(dat20, type!="1 contradiction"))

#### Table 4 Information ####


#### Demographics for 2020 + 2022 #### 


## age ##
dat20$age <- 2020 - dat20$birthyr

dat22$age <- 2022 - dat22$birthyr
dat22$age <- 2022-dat22$age

# education #

dat22$college_grad <- ifelse(dat22$educ < 5, 0, 1)
dat20$college_grad <- ifelse(dat20$educ < 5, 0, 1)

## race -- let's do white fraction for clarity
table(dat20$race)
dat20$white <- ifelse(dat20$race == 1, 1, 0)
dat22$white <- ifelse(dat22$race == 1, 1, 0)


## interest in politics

dat20$interested <- ifelse(dat20$newsint == 1, 1, 0)
dat22$interested <- ifelse(dat22$newsint == 1, 1, 0)

## knowledge

dat20$knowledge <- ifelse(dat20$CC20_310a == 2 & dat20$CC20_310b == 1, 1, 0)
dat22$knowledge <- ifelse(dat22$CC22_310a == 2 & dat22$CC22_310b == 2, 1, 0)

## set number of contradictions to numeric

dat20 <- dat20 %>%
  mutate(contradiction = case_when(
    type == "No contradictions" ~ 0,
    type == "1 contradiction" ~ 1,
    type == "2 contradictions" ~ 2,
    TRUE ~ NA_real_  # If there are other values, set them to NA
  ))

table(dat20$interested, dat20$contradiction)
dat22 <- dat22 %>%
  mutate(contradiction = case_when(
    type == "No contradictions" ~ 0,
    type == "1 contradiction" ~ 1,
    type == "2 contradictions" ~ 2,
    TRUE ~ NA_real_  # If there are other values, set them to NA
  ))

generate_table <- function(data, vars_of_interest) {
  
  # Create a function to process each data frame
  process_df <- function(df) {
    df %>%
      group_by(contradiction) %>%
      summarise(across(vars_of_interest, mean, na.rm = TRUE)) %>%
      pivot_longer(cols = -contradiction, names_to = "Number of Contradictions", values_to = "Mean")
  }
  
  # Process dat20 and dat22 separately
  processed_data <- process_df(data)
  
  # Combine the processed data frames
  
  # Pivot the combined data frame to wide format for each panel
  output_df <<- processed_data %>%
    pivot_wider(names_from = contradiction,
                values_from = Mean)
  
}

generate_table(dat20, c("age", "college_grad", "white", "interested", "knowledge"))
demo_20 <- output_df
generate_table(dat22, c("age", "college_grad", "white", "interested", "knowledge"))
demo_22 <- output_df[, !(names(output_df) == "Number of Contradictions")]

combined_demo <- cbind(demo_20, demo_22)

## format and rescale

combined_demo[1, 2:7] <- round(combined_demo[1, 2:7], digits = 1)
combined_demo[2, 2:7] <- round(combined_demo[2, 2:7] * 100, digits = 1)
combined_demo[3, 2:7] <- round(combined_demo[3, 2:7] * 100, digits = 1)
combined_demo[4,2:7] <- round(combined_demo[4, 2:7] * 100, digits = 1)
combined_demo[5, 2:7] <- round(combined_demo[5, 2:7] * 100, digits = 1)

combined_demo[, 1] <- c("Age", "College Graduate", "White", "Interested in Politics", "Knows who controls Congress")

combined_demo_output <- kbl(
  combined_demo,
  format = "latex",
  align = c("l", "c", "c", "c", "c", "c", "c"),
  linesep = "",
  escape = FALSE,
  booktabs = TRUE
) |>
  add_header_above(c(" " = 1, "2020" = 3, "2022" = 3)) |>
  row_spec(8, hline_after = TRUE)

combined_demo_output |>
  write_lines("../output/demographics.tex")
print("Table 4 created")

#### Table 5: Binaries ####

binaries <- c("hispanic", "child18", "trans", "pew_bornagain")


dat22 = apply_labels(dat22,
                     pew_bornagain = "Born-Again",
                     trans = "Transgender",
                     child18 = "Child Under 18",
                     hispanic = "Hispanic",
                     gender = "Gender"
)
dat22$trans[dat22$trans==3] <- NA
dat22$votereg_b <- dat22$votereg
dat22$votereg_b[dat22$votereg_b==3] <- NA
dat22$inconsistent_dummy <- 0
dat22$inconsistent_dummy[dat22$inconsistent == 1 | dat22$inconsistenta == 1] <- 1
dat20$inconsistent_dummy <- 0
dat20$inconsistent_dummy[dat20$inconsistent == 1 | dat20$inconsistenta == 1] <- 1
for (var in binaries) {
  formula_str <- paste0("inconsistent_dummy ~", var)
  t_test_result <- tidy(t.test(as.formula(formula_str), data = dat22))
  t_test_result$Question <- with(dat22, var)
  t_test_result$Respondents <- sum(dat22[[var]] == 1, na.rm = TRUE)
  if (var == "hispanic") {
    combined_df <- t_test_result %>% dplyr::select(Question, Respondents, estimate1, estimate2, estimate, p.value,)
  } else {
    combined_df <- t_test_result %>% dplyr::select(Question, Respondents, estimate1, estimate2, estimate, p.value) %>% rbind(combined_df)
  }
}
combined_df <- rename(combined_df, Difference = estimate, "Self-Identified Yes" = "estimate1", "Self-Identified No" = "estimate2")
binary_output <- with(combined_df, kable(combined_df, "latex", digits=3, format.args = list(nsmall = 3), booktabs = TRUE)) 
writeLines(binary_output, "../output/binary_questions.tex")
print("Table 5 created")

#### Table 6 and 7: Voting Behavior for Groups #### 


# Create House vote variable
# Recode vote preference variable so that there is one variable for whether or not respondent is voting for a House Dem and another for whether or not respondent is voting for a House Rep
dat22$HouseVote <- 0
dat22$HouseVote[dat22$CC22_367_voted==1 & dat22$HouseCand1Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367==1 & dat22$HouseCand1Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367_voted==2 & dat22$HouseCand2Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367==2 & dat22$HouseCand2Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367_voted==3 & dat22$HouseCand3Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367==3 & dat22$HouseCand3Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367_voted==4 & dat22$HouseCand4Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367==4 & dat22$HouseCand4Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367_voted==6 & dat22$HouseCand6Party=="Democratic"] <- 1
dat22$HouseVote[dat22$CC22_367==6 & dat22$HouseCand6Party=="Democratic"] <- 1

dat22$HouseVote[dat22$CC22_367_voted==2 & dat22$HouseCand2Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==2 & dat22$HouseCand2Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367_voted==3 & dat22$HouseCand3Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==3 & dat22$HouseCand3Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367_voted==4 & dat22$HouseCand4Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==4 & dat22$HouseCand4Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367_voted==5 & dat22$HouseCand5Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==5 & dat22$HouseCand5Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367_voted==6 & dat22$HouseCand6Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==6 & dat22$HouseCand6Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367_voted==7 & dat22$HouseCand7Party=="Republican"] <- 2
dat22$HouseVote[dat22$CC22_367==7 & dat22$HouseCand7Party=="Republican"] <- 2

dat22$HouseVote_post <- 0
dat22$HouseVote_post[dat22$tookpost==1] <- NA
dat22$HouseVote_post[dat22$CC22_412==1 & dat22$HouseCand1Party_post=="Democratic"] <- 1
dat22$HouseVote_post[dat22$CC22_412==2 & dat22$HouseCand2Party_post=="Democratic"] <- 1
dat22$HouseVote_post[dat22$CC22_412==3 & dat22$HouseCand3Party_post=="Democratic"] <- 1
dat22$HouseVote_post[dat22$CC22_412==4 & dat22$HouseCand4Party_post=="Democratic"] <- 1
dat22$HouseVote_post[dat22$CC22_412==6 & dat22$HouseCand6Party_post=="Democratic"] <- 1

dat22$HouseVote_post[dat22$CC22_412==2 & dat22$HouseCand2Party_post=="Republican"] <- 2
dat22$HouseVote_post[dat22$CC22_412==3 & dat22$HouseCand3Party_post=="Republican"] <- 2
dat22$HouseVote_post[dat22$CC22_412==4 & dat22$HouseCand4Party_post=="Republican"] <- 2
dat22$HouseVote_post[dat22$CC22_412==5 & dat22$HouseCand5Party_post=="Republican"] <- 2
dat22$HouseVote_post[dat22$CC22_412==6 & dat22$HouseCand6Party_post=="Republican"] <- 2
dat22$HouseVote_post[dat22$CC22_412==7 & dat22$HouseCand7Party_post=="Republican"] <- 2

prop.table(table(dat22[dat22$type == "No contradictions", "hispanic"]))

dat22$HouseDemocrat <- car::recode(dat22$HouseVote, "0=0; 1=1; 2=0")
dat22$HouseRepublican <- car::recode(dat22$HouseVote, "0:1=0; 2=1")

dat22$Trump <- car::recode(dat22$presvote20post, "1=0; 2=1; 3:5=0")
dat22$Trump[dat22$presvote20post==6] <- NA
dat22$Biden <- car::recode(dat22$presvote20post, "1=1; 2=0; 3:5=0")
dat22$Biden[dat22$presvote20post==6] <- NA
dat22$Republican <- car::recode(dat22$pid7, "1:4=0; 5:7=1; 8=0")
## Transgender 

print("Results for Table 6:")
print("Transgender vote, all respondents")
dat22 %>% filter(transgender==1) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))
print("Transgender vote, no contradictors")
dat22 %>% filter(transgender==1 & type == "No contradictions" ) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))
print("Transgender vote, take out twice contradictors")
dat22 %>% filter(transgender==1 & type != "2 contradictions" ) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))


# Hispanic #
print("Results for Table 7")
print("Hispanic vote, all respondents")
dat22 %>% filter(hispanic==1 ) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))
print("Hispanic vote, no contradictions")
dat22 %>% filter(hispanic==1 & type == "No contradictions" ) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))

print("Hispanic vote, take out twice contradictors")
dat22 %>% filter(hispanic==1 & type != "2 contradictions" ) %>%
  summarise(Trump = round(weighted.mean(Trump*100, commonweight, na.rm=TRUE),1),
            Trumpraw = round(mean(Trump, na.rm=TRUE),3),
            Biden = round(weighted.mean(Biden*100, commonweight, na.rm=TRUE),1),
            Republican = round(weighted.mean(Republican*100, commonweight, na.rm=TRUE),1),
            HouseRepublican = round(weighted.mean(HouseRepublican*100, commonweight, na.rm=TRUE),1))


